﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Xml.Linq;
using System.Data;

namespace VietStar.Library.Commom.IO
{
    public class FileReader
    {
        public FileReader()
        { }

        /// <summary>
        /// return connection string from xml config file
        /// </summary>
        /// <param name="filename">xml file location</param>
        /// <returns>string</returns>
        public string ReadXmlConfigFile(string filename)
        {
            string s = "";
            try
            {
                XElement root = XElement.Load(filename);
                XElement sv = root.Element("server");
                XElement db = root.Element("database");
                XElement us = root.Element("user");
                XElement ps = root.Element("pass");
                if((sv.Value != null) && (db.Value != null) && (us.Value != null) && (ps.Value != null))
                    s = "Data Source= " + sv.Value + ";Initial Catalog= " + db.Value + " ;User Id=" + us.Value + ";Password=" + ps.Value + "";
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return s;
        }

        /// <summary>
        /// save connection string to xml file
        /// </summary>
        /// <param name="tsv">server name</param>
        /// <param name="tdb">database name</param>
        /// <param name="tus">user name</param>
        /// <param name="tps">user password</param>
        /// <param name="filename">xml file location</param>
        /// <returns>bool</returns>
        public bool SaveXmlConfigFile(string tsv, string tdb, string tus, string tps, string filename)
        {
            bool s = false;
            try
            {
                XElement root = new XElement("config");
                XElement sv = new XElement("server", tsv);
                XElement db = new XElement("database", tdb);
                XElement us = new XElement("user", tus);
                XElement ps = new XElement("pass", tps);
                root.Add(sv);
                root.Add(db);
                root.Add(us);
                root.Add(ps);
                root.Save(filename);
                s = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return s;
        }
    }
}
